package com.teragadgets.android.comics.appengine;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class UpdateComicsServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(AddComicServlet.class
			.getName());

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {

			String query = "select from " + WebComic.class.getName();
			try {
				long id = Long.parseLong(req.getParameter("id"));
				query += " where id==" + id;
			} catch (Exception e) {
			}
			List<WebComic> webComics = (List<WebComic>) pm.newQuery(query)
					.execute();

			for (WebComic c : webComics) {

				resp.getWriter().println("<br />" + c.getName() + "<br />");
				boolean foundNew = loadNextComic(c, pm, resp);
				if (foundNew)
					resp.getWriter().println("Found new comic ^_^ <br />");
				else
					resp.getWriter().println("No new comics <br />");
			}

		} finally {
			pm.close();
		}

		log.info("Web Comics Updated");
		// resp.sendRedirect("/index.jsp");
	}

	private boolean loadNextComic(WebComic c, PersistenceManager pm,
			HttpServletResponse resp) {
		String currentPage = c.getLatestComicURL();
		String data = loadPage(currentPage);

		// load the first comic if this is the first run
		if (c.getLatestComic() == 0) {
			c.setLatestComic(c.getLatestComicURL());
			addComic(c, data, pm, resp);
		}

		// Search for an enabled next button, meaning there is a new comic
		Pattern pattern = Pattern.compile(c.getNextButtonRegex());
		Matcher matcher = pattern.matcher(data);

		// if new comic exists
		if (matcher.find() && !matcher.group(1).equals("#")) {
			String nextPage = matcher.group(1);
			c.setLatestComic(nextPage);
			data = loadPage(c.getURL() + nextPage);
			addComic(c, data, pm, resp);
			// loadNextComic(c, pm);
			return true;
		}
		return false;
	}

	private void addComic(WebComic c, String data, PersistenceManager pm,
			HttpServletResponse resp) {

		String name;
		try {
			name = parsePage(data, c.getComicNameRegex());
		} catch (Exception e) {
			name = "";
		}
		String url;
		try {
			url = parsePage(data, c.getComicImageRegex());
			if (url.startsWith("/")) {
				url = c.getURL() + url.substring(1);
			} else if (!url.startsWith("http") && !url.startsWith("www"))
				url = c.getURL() + url;
			// Penny Arcade next button goes to blank pages if they didn't post
			// a comic that day
		} catch (Exception e) {
			url = "";
			c.decreaseComicCount();
			return;
		}
		String altText;
		try {
			altText = parsePage(data, c.getComicAltTextRegex());
		} catch (Exception e) {
			altText = "";
		}

		Comic comic = new Comic(name, url, altText, c.getLatestComic(), c
				.getID());
		pm.makePersistent(comic);

	}

	private String parsePage(String data, String regex) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(data);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return null;
	}

	private String loadPage(String nextPage) {
		String content = null;
		URLConnection connection = null;
		try {
			connection = new URL(nextPage).openConnection();
			Scanner scanner = new Scanner(connection.getInputStream());
			scanner.useDelimiter("\\Z");
			content = scanner.next();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return content;
	}
}
